﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using SHZY.BaseData.Entitys.Common.Dto.PrintData;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Interfaces.Common;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.Models.NPOI;
using SHZY.Common.Security;
using SHZY.DataEncryption;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：打印数据源设置.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "ComBasePrintData", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBasePrintDataService : IComBasePrintDataService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBasePrintDataEntity> _repository;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个 <see cref="ComBasePrintDataService"/> 类型的新实例.
    /// </summary>
    public ComBasePrintDataService(
        ISqlSugarRepository<ComBasePrintDataEntity> comBasePrintDataRepository,
        ISqlSugarClient context,
        IDataInterfaceService dataInterfaceService,
        IUserManager userManager)
    {
        _repository = comBasePrintDataRepository;
        _db = context.AsTenant();
        _dataInterfaceService = dataInterfaceService;
        _userManager = userManager;
    }

    /// <summary>
    /// 获取所有打印数据源设置.
    /// </summary>
    /// <returns></returns>
    [HttpGet("All")]
    public async Task<dynamic> GetListAll()
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1)
            .OrderBy(x => x.Code).ToListAsync();
        return new { list = data.Adapt<List<ComBasePrintDataInfoOutput>>() };
    }

    /// <summary>
    /// 获取打印数据源设置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBasePrintDataInfoOutput>();
    }

    /// <summary>
    /// 获取打印数据源设置列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] ComBasePrintDataListQueryInput input)
    {
        var data = await _repository.Context.Queryable<ComBasePrintDataEntity>()
            .LeftJoin<DictionaryDataEntity>((it, a) => it.DbLinkId == a.EnCode && a.DictionaryTypeId == "9e7b2d0c690f4562b13e1215e449c222")
            .WhereIF(!string.IsNullOrEmpty(input.code), it => it.Code.Contains(input.code))
            .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Code.Contains(input.keyword) || it.Name.Contains(input.keyword))
            .Where(it => it.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.CreatorTime,OrderByType.Desc)
            .Select((it, a) => new ComBasePrintDataListOutput
            {
                id = it.Id,
                code = it.Code,
                name = it.Name,
                dbLinkId = SqlFunc.IF(it.DbLinkId == "0").Return("默认数据库").End(a.FullName),
                sqlTemplate = it.SqlTemplate,
                enabledMark = SqlFunc.IF(it.EnabledMark == 1).Return("正常").End("停用")
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<ComBasePrintDataListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建打印数据源设置.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task Create([FromBody] ComBasePrintDataCrInput input)
    {
        if (await _repository.AnyAsync(x => (x.Code == input.code || x.Name == input.name) && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBasePrintDataEntity>();
        entity.Id = SnowflakeIdHelper.NextId();
        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 更新打印数据源设置.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task Update(string id, [FromBody] ComBasePrintDataUpInput input)
    {
        if (await _repository.AnyAsync(x => (x.Code == input.code || x.Name == input.name) && x.DeleteMark == null && x.Id != input.id))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBasePrintDataEntity>();
        var isOk = await _repository.Context.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).CallEntityMethod(m => m.LastModify()).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
    }

    /// <summary>
    /// 导出打印数据源设置.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] ComBasePrintDataListQueryInput input)
    {
        var exportData = new List<ComBasePrintDataListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<ComBasePrintDataListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"数据源编码\",\"field\":\"code\"},{\"value\":\"数据源名称\",\"field\":\"name\"},{\"value\":\"数据连接\",\"field\":\"dbLinkId\"},{\"value\":\"SQL语句\",\"field\":\"sqlTemplate\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "打印数据源设置.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<ComBasePrintDataListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 删除打印数据源设置.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        var isOk = await _repository.Context.Updateable<ComBasePrintDataEntity>().SetColumns(it => new ComBasePrintDataEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(x => x.Id == id).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }

    /// <summary>
    /// 批量删除打印数据源设置.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task BatchRemove([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<ComBasePrintDataEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除打印数据源设置
                var isOk = await _repository.Context.Updateable<ComBasePrintDataEntity>().SetColumns(it => new ComBasePrintDataEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 获取打印数据源设置无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    private async Task<dynamic> GetNoPagingList([FromQuery] ComBasePrintDataListQueryInput input)
    {
        return await _repository.Context.Queryable<ComBasePrintDataEntity>()
            .LeftJoin<DictionaryDataEntity>((it, a) => it.DbLinkId == a.EnCode && a.DictionaryTypeId == "9e7b2d0c690f4562b13e1215e449c222")
            .WhereIF(!string.IsNullOrEmpty(input.code), it => it.Code.Contains(input.code))
            .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.Code.Contains(input.keyword) || it.Name.Contains(input.keyword))
            .Where(it => it.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.CreatorTime, OrderByType.Desc)
            .Select((it, a) => new ComBasePrintDataListOutput
            {
                id = it.Id,
                code = it.Code,
                name = it.Name,
                dbLinkId = SqlFunc.IF(it.DbLinkId == "0").Return("默认数据库").End(a.FullName),
                sqlTemplate = it.SqlTemplate,
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), input.sidx + " " + input.sort).ToListAsync();
    }
}